#include "rtc.h"
#include "esp_log.h"
#include "esp_sntp.h"
#include "esp_system.h"
#include "esp_timer.h"
#include "sys/time.h"

static const char *TAG = "RTC";

void cl_rtc_init() {
  // 检查当前时间是否有效
  time_t now;
  struct tm timeinfo;
  time(&now);
  localtime_r(&now, &timeinfo);

  // 如果时间已经有效，则不需要设置
  if (timeinfo.tm_year >= (2020 - 1900)) {
    ESP_LOGI(TAG, "RTC already has valid time, no need to set");
    return;
  }

  // 设置编译时间为RTC时间
  char build_time[64];
  sprintf(build_time, "%s %s", __DATE__, __TIME__);
  struct tm build_tm;
  strptime(build_time, "%b %d %Y %H:%M:%S", &build_tm);
  time_t build_time_t = mktime(&build_tm);

  struct timeval tv = {.tv_sec = build_time_t, .tv_usec = 0};
  settimeofday(&tv, NULL);

  ESP_LOGI(TAG, "RTC initialized with build time: %s", build_time);
}

time_t rtc_read_timestamp() {
  time_t now;
  time(&now);
  return now;
}

void rtc_write_timestamp(time_t timestamp) {
  struct timeval tv = {.tv_sec = timestamp, .tv_usec = 0};
  settimeofday(&tv, NULL);
}

void rtc_timestamp_to_time(time_t timestamp, struct tm *timeinfo) {
  localtime_r(&timestamp, timeinfo);
}

time_t rtc_time_to_timestamp(struct tm *timeinfo) { return mktime(timeinfo); }